﻿var shPathServiceUrl = 'http://localhost:80/sh_path';
var map;
var markersArray = [];
var geocoder;
var infowindow = new google.maps.InfoWindow();
var Polyline;
function initMap() {
    geocoder = new google.maps.Geocoder();
    var Spb = new google.maps.LatLng(59.934, 30.537);
    var mapOptions = { zoom: 10, center: Spb, mapTypeId: google.maps.MapTypeId.ROADMAP  };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    google.maps.event.addListener(map, 'click', mapClicked);
}
function addMarker(location) {
    if (markersArray.length == 2) {
        var latLng = markersArray[1].position;
        deleteOverlays();
        addMarker(latLng);
    }
    marker = new google.maps.Marker({ position: location, map: map, draggable: true });
    markersArray.push(marker);

    google.maps.event.addListener(marker, 'click', function (event) {
        markerClicked(this, event)
    });

    google.maps.event.addListener(marker, 'dragend', markerDragged);
    
    deletePolyline();
    if (markersArray.length == 2) GetRoute();
}
function mapClicked(event) {
    addMarker(event.latLng);
}
function markerClicked(marker,event) {
    //infowindow.setContent(marker.title);
    decodeLatLng(marker.position)
    infowindow.open(map, marker);
}
function markerDragged(event) {
    //alert('marker drugged!');
    GetRoute();
}
// Removes the overlays from the map, but keeps them in the array 
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            var marker = markersArray[i];
            marker.setMap(null);
        }
    }
}
// Shows any overlays currently in the array 
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}
// Deletes all markers in the array by removing references to them 
function deleteOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

function decodeLatLng(latlng) {
geocoder.geocode({ 'latLng': latlng },
    function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                infowindow.setContent(results[1].formatted_address);
            }
        }
        else infowindow.setContent("Unknown place"); //return ""; //{ alert("Geocoder failed due to: " + status); } 
    });
}
function deletePolyline() {
    if (Polyline) {
        Polyline.setMap(null);
        Polyline = null;
    }
}

function GetRoute() {
    if (markersArray[0] && markersArray[1]) {
	var date = new Date();
        //Works with GET
        var query_str = shPathServiceUrl + 
                        '?lat1=' + markersArray[0].position.lat() +
                        '&lng1=' + markersArray[0].position.lng() +
                        '&lat2=' + markersArray[1].position.lat() +
                        '&lng2=' + markersArray[1].position.lng() +
                        '&path-type=' + $('#form-route-type input:radio:checked').val() +
                        '&rand=' + date.getMilliseconds().toString();
        $.get(query_str, function (data) {
            alert(data);
            var resp = $.parseJSON(data);
            if (resp == "err_code_1")
            {
                alert("There is no way between given points");
            }
            else
            {
                var LatLangAr = [];
                //            alert(resp)
                for (i = 0; i < resp.length; i+=2 ) {
                    LatLangAr.push(new google.maps.LatLng(resp[i], resp[i+1]));
                }
                var PolylineOptions = { map: map, path: LatLangAr }; //, strokeOpacity: 0, strokeWeight: 4 };

                deletePolyline();
                Polyline = new google.maps.Polyline(PolylineOptions);
            }
        });
    } else alert('You haven\'t chosen two points on the map');
}
